package org.example.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.example.entity.Menu;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.exception.LoginException;
import org.example.service.IMenuService;
import org.example.service.IRoleService;
import org.example.service.IUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final IUserService userService;
    private final IRoleService roleService;
    private final IMenuService menuService;
    //登录调用的方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.
        User user=userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,username));
        if (user==null) throw new UsernameNotFoundException("用户不存在");
        //2.获取用户所有的角色列表
        List<Role> roleList=roleService.listByUserId(user.getUserId());
        Long[] roleIds=roleList.stream().mapToLong(Role::getRoleId).boxed().toArray(Long[]::new);
        //3.根据角色获取所有菜单
        List<Menu> menuList=menuService.listByRoleIds(roleList.stream().mapToLong(Role::getRoleId).boxed().toArray(Long[]::new));

        Set<String> roleNames=roleList.stream().map(Role::getRoleKey).collect(Collectors.toSet());
        Set<String> perms=menuList.stream()
                .filter(menu -> StringUtils.hasText(menu.getPerms()))
                .map(Menu::getPerms).collect(Collectors.toSet());
        UserDetailsImpl userDetails=new UserDetailsImpl();

        userDetails.setRoleKeySet(roleNames);
        userDetails.setPermsSet(perms);
        userDetails.setUsername(user.getUserName());
        userDetails.setPassword(user.getPassword());
        userDetails.setStatus(user.getStatus());

        return userDetails;
    }
}
